<?php


namespace Units;


class ChunkRouter
{

    private $data=[];
    private $center=[];
    /**获取每个路线的平均站点数量
     * @param $data
     * @return float
     */
    public static function getAvagePointsPerRouter( $data , $max_stops ){
        $allPoints =  count( $data);
        // $allWeight = array_sum(array_map( function ($val){
        // return $val['GrossWeight'];
        //  },$this->data ));
        $num1 = ceil( $allPoints / $max_stops);
        $num2 = ceil( $allPoints / $num1 );
        return $num2;
    }



    /**
     * 检查每条线路不超过规定的点数和磅数
     * 超出点数的线路进行分割
     * @param $data  区域上所有点
     * @param int $max_stops  最大站数
     * @param int $max_weight
     * @return array
     */
    public static function split( $data ,$max_stops =17 , $max_weight=6800 ){
        $return = [];
        $stop = 0;
        $weight = 0;

        $routerResult =[];
        $len = count( $data ) - 1;
        $average = self::getAvagePointsPerRouter( $data , $max_stops );
        foreach ( $data as $key=>$val ){
                $stop++;
                $weight = $weight + $val['GrossWeight'];
                if( $stop <= $average && $weight<= $max_weight ) {
                    if( $key== $len ) {
                        $routerResult[] = $val;
                        $return[] = $routerResult;
                    }else{
                        $routerResult[] = $val;
                    }
                }
                elseif ( $key == $len && $stop > $average && $weight > $max_weight  ) {
                        $routerResult=[];
                        $routerResult[] =$val;
                        $return[] = $routerResult;
                }
                else{
                    $return[] = $routerResult;
                    $stop=0;
                    $weight=0;
                    $routerResult=[];
                    $routerResult[] =$val;
                }


        }

        return $return;
    }

    public static function getFreeRouterKey ( $data , $maxStop ,$elementCount )  {

              $len = count( $data );
              for( $i = $len-1; $i <= $len - $elementCount;$i-- ) {
                   if( count($data[$i]) < $elementCount ) {
                       return $i;
                   }
              }
              return false;

    }


}